<?php

namespace think\wework\Api;

use think\wework\Crypt\PrpCrypt;
use think\wework\Abstracts\WeworkApi;
use think\wework\Http\ClientFactory;

class JsSdk extends WeworkApi
{
    private static ?JsSdk $instance = null;
    public static function getInstance(): JsSdk
    {
        if(!self::$instance instanceof JsSdk) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    public function __construct()
    {
        parent::__construct();
        $this->httpClient = ClientFactory::create();
        $this->jsApiTicket = (new JsApiTicket())->get();
        $this->ticket = (new Ticket())->get();
    }

    /**
     * @param string $url
     * @return array
     */
    public function getConfig(string $url): array
    {
        $appId = $this->corpId;

        $timestamp = $this->getTimestamp();

        $nonceStr = $this->getNonceStr();

        $signature = sha1("jsapi_ticket=$this->jsApiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url");

        return compact('appId', 'timestamp', 'nonceStr', 'signature');
    }

    /**
     * @return array
     */
    public function getChooseInvoiceConfig(): array
    {
        $timestamp = $this->getTimestamp();

        $nonceStr = $this->getNonceStr();

        $array = ['INVOICE', $this->corpId, $timestamp, $nonceStr, $this->ticket];

        sort($array, SORT_STRING);

        $str = implode($array);

        $cardSign = sha1($str);

        return compact('timestamp', 'nonceStr', 'cardSign');
    }

    /**
     * @return int
     */
    protected function getTimestamp(): int
    {
        return time();
    }

    /**
     * @return string
     */
    protected function getNonceStr(): string
    {
        return (new PrpCrypt(null))->getRandomStr();
    }
}
